Link to this headingBash Programing
Bash variables and command substitution
Scripting in bash
Learn to make bash scripts
Check your Bash Scripts
Pure Bash Bible
Script:
Link to this headingStrings
Link to this headingTrim leading and trailing white-space from string
This is an alternative to sed, awk, perl and other tools. The function below works by finding all leading and trailing white-space and removing it from the start and end of the string. The : built-in is used in place of a temporary variable.
Example Function:
Example Usage:
Link to this headingTrim all white-space from string and truncate spaces
This is an alternative to sed, awk, perl and other tools. The function below works by abusing word splitting to create a new string without leading/trailing white-space and with truncated spaces.
Example Function:
Example Usage:
Link to this headingUse regex on a string
The result of bash’s regex matching can be used to replace sed for a large number of use-cases.
CAVEAT: This example only prints the first matching group. When using multiple capture groups some modification is needed.
Example Function:
Example Usage:
Example Usage in script:
Link to this headingSplit a string on a delimiter
This is an alternative to cut, awk and other tools.
Example Function:
Example Usage:
Link to this headingChange a string to lowercase
Example Function:
Example Usage:
Link to this headingChange a string to uppercase
Example Function:
Example Usage:
Link to this headingReverse a string case
Example Function:
Example Usage:
Link to this headingTrim quotes from a string
Example Function:
Example Usage:
Link to this headingStrip all instances of pattern from string
Example Function:
Example Usage:
Link to this headingStrip first occurrence of pattern from string
Example Function:
Example Usage:
Link to this headingStrip pattern from start of string
Example Function:
Example Usage:
Link to this headingStrip pattern from end of string
Example Function:
Example Usage:
Link to this headingPercent-encode a string
Example Function:
Example Usage:
Link to this headingDecode a percent-encoded string
Example Function:
Example Usage:
Link to this headingCheck if string contains a sub-string
Using a test:
Using a case statement:
Link to this headingCheck if string starts with sub-string
Link to this headingCheck if string ends with sub-string
Link to this headingLength of string
Link to this headingArrays
Link to this headingReverse an array
Enabling extdebug allows access to the BASH_ARGV array which stores the current function’s arguments in reverse.
Example Function:
Example Usage:
Link to this headingRemove duplicate array elements
Create a temporary associative array. When setting associative array values and a duplicate assignment occurs, bash overwrites the key. This allows us to effectively remove array duplicates.
Example Function:
Example Usage:
Link to this headingRandom array element
Example Function:
Example Usage:
Link to this headingCycle through an array
Each time the printf is called, the next array element is printed. When the print hits the last array element it starts from the first element again.
Link to this headingToggle between two values
This works the same as above, this is just a different use case.
Link to this headingLoops
Link to this headingLoop over a range of numbers
Alternative to seq.
Link to this headingLoop over a variable range of numbers
Alternative to seq.
Link to this headingLoop over an array
Link to this headingLoop over an array with an index
Link to this headingLoop over the contents of a file
Link to this headingLoop over files and directories
Don’t use ls.
Link to this headingFile Handling
Link to this headingRead a file to a string
Alternative to the cat command.
Read a file to an array (by line)
Alternative to the cat command.
Link to this headingGet the first N lines of a file
Alternative to the head command.
Example Function:
Example Usage:
Link to this headingGet the last N lines of a file
Alternative to the tail command.
Example Function:
Example Usage:
Link to this headingGet the number of lines in a file
Alternative to wc -l.
Example Function (bash 4.x):
Example Function (bash 3.x):
This method uses less memory than the mapfile method and works in bash 3 but it is slower for bigger files.
Example Usage:
Link to this headingCount files or directories in directory
This works by passing the output of the glob to the function and then counting the number of arguments.
Example Function:
Example Usage:
Link to this headingCreate an empty file
Alternative to touch.
Link to this headingExtract lines between two markers
Example Function:
Example Usage:
Link to this headingFile Paths
Link to this headingGet the directory name of a file path
Alternative to the dirname command.
Example Function:
Example Usage:
Link to this headingGet the base-name of a file path
Alternative to the basename command.
Example Function:
Example Usage:
Link to this headingVariables
Link to this headingAssign and access a variable using a variable
Alternatively, on bash 4.3+:
Link to this headingName a variable based on another variable
Link to this headingEscape Sequences
Link to this headingText Colors
| Sequence | What does it do? | Value |
|---|---|---|
e[38;5;<NUM>m | Set text foreground color. | 0-255 |
e[48;5;<NUM>m | Set text background color. | 0-255 |
e[38;2;<R>;<G>;<B>m | Set text foreground color to RGB color. | R, G, B |
e[48;2;<R>;<G>;<B>m | Set text background color to RGB color. | R, G, B |
Link to this headingText Attributes
| Sequence | What does it do? |
|---|---|
e[m | Reset text formatting and colors. |
e[1m | Bold text. |
e[2m | Faint text. |
e[3m | Italic text. |
e[4m | Underline text. |
e[5m | Slow blink. |
e[7m | Swap foreground and background colors. |
Link to this headingCursor Movement
| Sequence | What does it do? | Value |
|---|---|---|
e[<LINE>;<COLUMN>H | Move cursor to absolute position. | line, column |
e[H | Move cursor to home position (0,0). | |
e[<NUM>A | Move cursor up N lines. | num |
e[<NUM>B | Move cursor down N lines. | num |
e[<NUM>C | Move cursor right N columns. | num |
e[<NUM>D | Move cursor left N columns. | num |
e[s | Save cursor position. | |
e[u | Restore cursor position. |
Link to this headingErasing Text
| Sequence | What does it do? |
|---|---|
e[K | Erase from cursor position to end of line. |
e[1K | Erase from cursor position to start of line. |
e[2K | Erase the entire current line. |
e[J | Erase from the current line to the bottom of the screen. |
e[1J | Erase from the current line to the top of the screen. |
e[2J | Clear the screen. |
e[2Je[H | Clear the screen and move cursor to 0,0. |
Link to this headingParameter Extension
Link to this headingIndirection
${!VAR} | Access a variable based on the value of VAR |
${!VAR*} | Expand to IFS separated list of variable names starting with VAR |
${!VAR@} | Expand to IFS separated list of variable names starting with VAR. If double-quoted, each variable name expands to a separate word. |
Link to this headingReplacement
| Parameter | What does it do? |
|---|---|
${VAR#PATTERN} | Remove shortest match of pattern from start of string. |
${VAR##PATTERN} | Remove longest match of pattern from start of string. |
${VAR%PATTERN} | Remove shortest match of pattern from end of string. |
${VAR%%PATTERN} | Remove longest match of pattern from end of string. |
${VAR/PATTERN/REPLACE} | Replace first match with string. |
${VAR//PATTERN/REPLACE} | Replace all matches with string. |
${VAR/PATTERN} | Remove first match. |
${VAR//PATTERN} | Remove all matches. |
Link to this headingLength
| Parameter | What does it do? |
|---|---|
${#VAR} | Length of var in characters. |
${#ARR[@]} | Length of array in elements. |
Link to this headingExpansion
${VAR:OFFSET} | Remove first N chars from variable. |
${VAR:OFFSET:LENGTH} | Get substring from N character to N character. (${VAR:10:10}: Get sub-string from char 10 to char 20) |
${VAR:: OFFSET} | Get first N chars from variable. |
${VAR:: -OFFSET} | Remove last N chars from variable. |
${VAR: -OFFSET} | Get last N chars from variable. |
${VAR:OFFSET:-OFFSET} | Cut first N chars and last N chars. |
Link to this headingCase Modification
| Parameter | What does it do? |
|---|---|
${VAR^} | Uppercase first character. |
${VAR^^} | Uppercase all characters. |
${VAR,} | Lowercase first character. |
${VAR,,} | Lowercase all characters. |
${VAR~} | Reverse case of first character. |
${VAR~~} | Reverse case of all characters. |
Link to this headingDefault Value
| Parameter | What does it do? |
|---|---|
${VAR:-STRING} | If VAR is empty or unset, use STRING as its value. |
${VAR-STRING} | If VAR is unset, use STRING as its value. |
${VAR:=STRING} | If VAR is empty or unset, set the value of VAR to STRING. |
${VAR=STRING} | If VAR is unset, set the value of VAR to STRING. |
${VAR:+STRING} | If VAR is not empty, use STRING as its value. |
${VAR+STRING} | If VAR is set, use STRING as its value. |
${VAR:?STRING} | Display an error if empty or unset. |
${VAR?STRING} | Display an error if unset. |
Link to this headingBrace Expansion
Link to this headingRanges
Link to this headingString Lists
Link to this headingConditional Expressions
Link to this headingFile Conditionals
| Expression | Value | What does it do? |
|---|---|---|
-a | file | If file exists. |
-b | file | If file exists and is a block special file. |
-c | file | If file exists and is a character special file. |
-d | file | If file exists and is a directory. |
-e | file | If file exists. |
-f | file | If file exists and is a regular file. |
-g | file | If file exists and its set-group-id bit is set. |
-h | file | If file exists and is a symbolic link. |
-k | file | If file exists and its sticky-bit is set |
-p | file | If file exists and is a named pipe (FIFO). |
-r | file | If file exists and is readable. |
-s | file | If file exists and its size is greater than zero. |
-t | fd | If file descriptor is open and refers to a terminal. |
-u | file | If file exists and its set-user-id bit is set. |
-w | file | If file exists and is writable. |
-x | file | If file exists and is executable. |
-G | file | If file exists and is owned by the effective group ID. |
-L | file | If file exists and is a symbolic link. |
-N | file | If file exists and has been modified since last read. |
-O | file | If file exists and is owned by the effective user ID. |
-S | file | If file exists and is a socket. |
Link to this headingFile Comparisons
file -ef file2 | If both files refer to the same inode and device numbers. |
file -nt file2 | If file is newer than file2 (uses modification time) or file exists and file2 does not. |
file -ot file2 | If file is older than file2 (uses modification time) or file2 exists and file does not. |
Link to this headingVariable Conditionals
| Expression | Value | What does it do? |
|---|---|---|
-o | opt | If shell option is enabled. |
-v | var | If variable has a value assigned. |
-R | var | If variable is a name reference. |
-z | var | If the length of string is zero. |
-n | var | If the length of string is non-zero. |
Link to this headingVariable Comparisons
| Expression | What does it do? |
|---|---|
var = var2 | Equal to. |
var == var2 | Equal to (synonym for =). |
var != var2 | Not equal to. |
var < var2 | Less than (in ASCII alphabetical order.) |
var > var2 | Greater than (in ASCII alphabetical order.) |
Link to this headingArithmetic Operators
Link to this headingAssignment
| Operators | What does it do? |
|---|---|
= | Initialize or change the value of a variable. |
Link to this headingArithmetic
| Operators | What does it do? |
|---|---|
* | Multiplication |
** | Exponentiation |
+= | Plus-Equal (Increment a variable.) |
-= | Minus-Equal (Decrement a variable.) |
*= | Times-Equal (Multiply a variable.) |
/= | Slash-Equal (Divide a variable.) |
%= | Mod-Equal (Remainder of dividing a variable.) |
Link to this headingBitwise
| Operators | What does it do? |
|---|---|
<< | Bitwise Left Shift |
<<= | Left-Shift-Equal |
>> | Bitwise Right Shift |
>>= | Right-Shift-Equal |
& | Bitwise AND |
&= | Bitwise AND-Equal |
| | Bitwise OR |
|= | Bitwise OR-Equal |
~ | Bitwise NOT |
^ | Bitwise XOR |
^= | Bitwise XOR-Equal |
Link to this headingLogical
| Operators | What does it do? |
|---|
Link to this headingMiscellaneous
| Operators | What does it do? | Example |
|---|---|---|
, | Comma Separator | ((a=1,b=2,c=3)) |
Link to this headingArithmetic
Link to this headingSimpler syntax to set variables
Link to this headingTernary Tests
Link to this headingTraps
Traps allow a script to execute code on various signals. In pxltrm (a pixel art editor written in bash) traps are used to redraw the user interface on window resize. Another use case is cleaning up temporary files on script exit.
Traps should be added near the start of scripts so any early errors are also caught.
Link to this headingDo something on script exit
Link to this headingIgnore terminal interrupt (CTRL+C, SIGINT)
Link to this headingReact to window resize
Link to this headingDo something before every command
Link to this headingDo something when a shell function or a sourced file finishes executing
Link to this headingPerformance
Link to this headingDisable Unicode
If unicode is not required, it can be disabled for a performance increase. Results may vary however there have been noticeable improvements in neofetch and other programs.
Link to this headingObsolete Syntax
Link to this headingShebang
Use #!/usr/bin/env bash instead of #!/bin/bash.
- The former searches the user’s
PATHto find thebashbinary. - The latter assumes it is always installed to
/bin/which can cause issues.
Link to this headingCommand Substitution
Use $() instead of ` `.
Link to this headingFunction Declaration
Do not use the function keyword, it reduces compatibility with older versions of bash.
Link to this headingInternal Varables
Get the location to the bash binary
Get the version of the current running bash process
Link to this headingOpen the user’s preferred text editor
Link to this headingGet the name of the current function
Link to this headingGet the host-name of the system
Link to this headingGet the architecture of the Operating System
Link to this headingGet the name of the Operating System / Kernel
This can be used to add conditional support for different Operating Systems without needing to call uname.
Link to this headingGet the current working directory
This is an alternative to the pwd built-in.
Link to this headingGet the number of seconds the script has been running
Link to this headingGet a pseudorandom integer
Each time $RANDOM is used, a different integer between 0 and 32767 is returned. This variable should not be used for anything related to security (this includes encryption keys etc).
Link to this headingInformation about the terminal
Get the terminal size in lines and columns (from a script)
This is handy when writing scripts in pure bash and stty/tput can’t be
called.
Example Function:
Example Usage:
Link to this headingGet the terminal size in pixels
CAVEAT: This does not work in some terminal emulators.
Example Function:
Example Usage:
Link to this headingGet the current cursor position
This is useful when creating a TUI in pure bash.
Example Function:
Example Usage:
Link to this headingConversion
Link to this headingConvert a hex color to RGB
Example Function:
Example Usage:
Link to this headingConvert an RGB color to hex
Example Function:
Example Usage:
Link to this headingCode Golf
Shorter for loop syntax
Link to this headingShorter infinite loops
Link to this headingShorter function declaration
Shorter if syntax
Simpler case statement to set variable
The : built-in can be used to avoid repeating variable= in a case statement. The $_ variable stores the last argument of the last command. : always succeeds so it can be used to store the variable value.
Link to this headingOthers
Use read as an alternative to the sleep command
Surprisingly, sleep is an external command and not a bash built-in.
CAVEAT: Requires bash 4+
Example Function:
Example Usage:
For performance-critical situations, where it is not economic to open and close an excessive number of file descriptors, the allocation of a file descriptor may be done only once for all invocations of read:
(See the generic original implementation at https://blog.dhampir.no/content/sleeping-without-a-subprocess-in-bash-and-how-to-sleep-forever)
Link to this headingCheck if a program is in the user’s PATH
Get the current date using strftime
Bash’s printf has a built-in method of getting the date which can be used in place of the date command.
CAVEAT: Requires bash 4+
Example Function:
Example Usage:
Link to this headingGet the username of the current user
CAVEAT: Requires bash 4.4+
Link to this headingGenerate a UUID V4
CAVEAT: The generated value is not cryptographically secure.
Example Function:
Example Usage:
Link to this headingProgress bars
This is a simple way of drawing progress bars without needing a for loop
in the function itself.
Example Function:
Example Usage:
Link to this headingGet the list of functions in a script
Link to this headingBypass shell aliases
Link to this headingBypass shell functions
Link to this headingRun a command in the background
This will run the given command and keep it running, even after the terminal or SSH connection is terminated. All output is ignored.
Link to this headingTemp cd in to folder
pushd / popd
Link to this headingArguments
Link to this headingEnvironment Variables
Link to this headingSetting Default Arguments in Bash
Timeout in scripts
Link to this headingBash File Testing
| Flag | Description |
|---|---|
| -b filename | Block special file |
| -c filename | Special character file |
| -d directoryname | Check for directory existence |
| -e filename | Check for file existence |
| -f filename | Check for regular file existence not a directory |
| -G filename | Check if file exists and is owned by effective group ID. |
| -g filename | true if file exists and is set-group-id. |
| -k filename | Sticky bit |
| -L filename | Symbolic link |
| -O filename | True if file exists and is owned by the effective user id. |
| -r filename | Check if file is a readable |
| -S filename | Check if file is socket |
| -s filename | Check if file is nonzero size |
| -u filename | Check if file set-ser-id bit is set |
| -w filename | Check if file is writable |
| -x filename | Check if file is executable |
Check if file exists: